package com.example.jenkinstest.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.jenkinstest.controller.util.RestTemplateUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class fileStogre {



    public static void main(String[] args) {
        upload();
//        dow();


    }

    private static void upload() {
        List<String> urlList = new ArrayList<>();
        String url = "https://xngwtest.jd.com/filestorage/$10000/file/image?siteId=kf_90001&isPermanent=0&path=/client";
        String path = "C:\\Users\\Administrator\\Desktop\\1.jpg";
        Timer timer = new Timer();
        ExecutorService executorService = Executors.newCachedThreadPool();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                for (int i = 0;i<100;i++){
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            String s = sendPostUplodFile(url, path);

//                            String fileId = getFileId(s);
//                            System.out.println(fileId);
                        }
                    });
                }

            }

        },0,1000);

        Timer timer2 = new Timer();

        timer2.schedule(new TimerTask() {
            @Override
            public void run() {
                timer.cancel();
            }
        },1000*60*10);

        System.out.println(new Date());
//        for (int i=0;i<100;i++){
//
//            String s = sendPostUplodFile(url, path);
//
//            String fileId = getFileId(s);
//            System.out.println(fileId);
//            System.out.println(i);
//            urlList.add(fileId);
//        }
//
//        System.out.println(JSONObject.toJSONString(urlList));
    }


    private static void dow() {

       List<String> urlList = Common.urlList;

        ExecutorService executorService = Executors.newCachedThreadPool();
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Random random = new Random();
                for (int i=0;i<5;i++){
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            int ran = random.nextInt(100);
                            System.out.println(ran);
                            RestTemplateUtils.RespBody respBody = RestTemplateUtils.get(urlList.get(ran), null);
                            System.out.println("111111111");
                        }
                    });
                }
            }
        },0,1000);


        Timer timer2 = new Timer();

        timer2.schedule(new TimerTask() {
            @Override
            public void run() {
                timer.cancel();
            }
        },1000*60*10);
    }

    public static String sendPostUplodFile(String url,String path) {
        DataOutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            //打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            //发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            String BOUNDARY = "----WebKitFormBoundary07I8UIuBx6LN2KyY";
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setReadTimeout(60000);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (conpatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            conn.connect();

            out = new DataOutputStream(conn.getOutputStream());
            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            //添加参数
            StringBuffer sb1 = new StringBuffer();
            sb1.append("--");
            sb1.append(BOUNDARY);
            sb1.append("\r\n");
            sb1.append("Content-Disposition: form-data;name=\"file\"");
            sb1.append("\r\n");
            sb1.append("\r\n");
            sb1.append("123");
            sb1.append("\r\n");
            out.write(sb1.toString().getBytes());
            //添加参数file
            File file = new File(path);
            StringBuffer sb = new StringBuffer();
            sb.append("--");
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"");
            sb.append("\r\n");
            sb.append("Content-Type: application/octet-stream");
            sb.append("\r\n");
            sb.append("\r\n");
            out.write(sb.toString().getBytes());

            DataInputStream in1 = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in1.read(bufferOut)) != -1) {
                out.write(bufferOut,0,bytes);
            }
            out.write("\r\n".getBytes());
            in1.close();
            out.write(end_data);

            //flush输出流的缓冲
            out.flush();
            //定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                // TODO: handle exception
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String getFileId(String result) {
        JSONObject json = JSONObject.parseObject(result);
        String fileId = "";
        if (result != null) {
            fileId =  json.getJSONObject("data").getJSONObject("thumbnailImage").getString("url");

        }

        return fileId;
    }
}
